<template>
	<div class="inviterMerch">
		<el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="120px">
			<el-form-item label="商户信息" v-if="this.option.rowConten" class="merchOption">
				<div class="top">
					<div>商户全称：{{ JSON.parse(this.option.rowConten).merchName }}</div>
					<div>联系电话：{{ JSON.parse(this.option.rowConten).merchPhone }}</div>
				</div>
				<div class="bottom">商户总部地址：{{ JSON.parse(this.option.rowConten).address }}</div>
			</el-form-item>

			<el-form-item label="出资方" prop="stakeRadio">
				<el-radio v-model="form.stakeRadio" v-for="item in form.stakeLis" :key="item.id" :label="item.id" @change="changestakeRadio">
					<span>{{ item.label }}</span>
					<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
						<div slot="content">{{ item.txt }}</div>
						<i class="el-icon-question" />
					</el-tooltip>
				</el-radio>
			</el-form-item>
			<el-form-item v-if="form.stakeRadio == 1" label="是否需要同意" prop="agreeRadio">
				<el-radio v-model="form.agreeRadio" v-for="item in form.agreeLis" :key="item.id" :label="item.id" @change="changeAgreeRadio">
					<span>{{ item.label }}</span>
					<!-- <el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
						<div slot="content">{{ item.txt }}</div>
						<i class="el-icon-question" />
					</el-tooltip> -->
				</el-radio>
				<p style="color: #afafaf;">指合作商户是否需要知道参与了本商户的超级会员</p>
			</el-form-item>

			<el-form-item label="优惠折扣" prop="discount">
				<el-input v-model="form.discount" style="width:50px" />
				折
			</el-form-item>
			<el-form-item style="color: #afafaf;">
				<p>用户实际支付计算规则：售价100元，100 * {{ (form.discount / 10).toFixed(2) }} = {{ (100 * (form.discount / 10)).toFixed(2) }} 元</p>
				<p>如折扣输入0将不参与折扣</p>
			</el-form-item>

			<el-form-item label="抽佣比例" prop="commission">
				<el-input v-model="form.commission" style="width:50px" :disabled="form.canCustomRate" />
				%
			</el-form-item>
			<el-form-item class="commission">
				<p>
					返佣规则：用户在合作商户使用超级会员优惠，会按照订单实收金额返佣，平台将在返佣金额抽取 {{ 100 - form.specialRoleRate }}% 服务费；
					<br />
					例：用户实收金额100元，平台服务费 {{ 100 - form.specialRoleRate }}% 。
					<br />
					返佣计算：100 * {{ form.commission }}% = {{ 100 * (form.commission / 100) }} 元
					<br />
					实际到账佣金计算：{{ 100 * (form.commission / 100) }} *（1 - {{ 100 - form.specialRoleRate }}%）=
					{{ (100 * (form.commission / 100) * (1 - (100 - form.specialRoleRate) / 100).toFixed(2)).toFixed(2) }}元
				</p>
			</el-form-item>

			<el-form-item label="积分奖励" prop="integralInput">
				<div style="float: left;">
					超级会员订单用户实付
					<el-input v-model="form.integralInput" style="width:50px" />
					元，奖励1个积分
				</div>

				<!-- <div @click="toSetVipPoints" style="float: left; margin-left:50px; color:#ffb72f; cursor: pointer;">去编辑积分抵扣规则</div> -->
			</el-form-item>
			<el-form-item>
				<el-radio v-model="form.integralRadio" v-for="item in form.integralReward" :key="item.id" :label="item.id">
					<span>{{ item.label }}</span>
					<!-- <el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
					    <div slot="content">{{ item.txt }}</div>
					    <i class="el-icon-question" />
					  </el-tooltip> -->
				</el-radio>
			</el-form-item>

			<el-form-item label="积分抵扣比例" prop="integralProp">
				<div style="float: left;">
					按订单金额
					<el-input v-model="form.integralProp" style="width:50px" @change="changeIntegralProp" />
					%抵扣，
					<span v-if="pointsConfig.enableUsePoints">每{{ pointsConfig.baseUseAmount }}个积分抵扣1元</span>
					<span v-else>未开启积分抵扣规则</span>
				</div>
				<div @click="toSetVipPoints" style="float: left; margin-left:50px; color:#ffb72f; cursor: pointer;">去编辑积分抵扣规则</div>
			</el-form-item>
			<el-form-item class="commission">
				<p>
					指用户在当前商户消费可使用积分抵扣现金，抵扣的优惠都有本商户承担，抵扣计算规则如下：
					<br />
					例：订单金额100元
					<br />
					可用积分数量： 100 * {{ form.integralProp }}% * {{ pointsConfig.baseUseAmount }} =
					{{ (100 * (form.integralProp / 100) * pointsConfig.baseUseAmount).toFixed() }}
				</p>
			</el-form-item>

			<el-form-item>
				<el-button @click="back">返回</el-button>
				<el-button type="primary" @click="submitForm('form')">确定修改</el-button>
			</el-form-item>

			<countdown-popo v-if="countdown.showPopup" :count-num="countdown.num" :jump-url="countdown.jumpUrl" :msg="countdown.msg" />
		</el-form>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import {
	newInviteBusiness,
	searchBusinessByPhone,
	getSuperMemberRateConfig,
	modifyDiscountAndRakeRate,
	saveMarketingAccount,
	getSubsidyAccountBalance,
	getBusinessInfo,
	checkSubsidyRelation
} from '@/api/business';
import { getPointsConfig } from '@/api/points';
import countdownPopo from '../../components/countdown-popo/index.vue';
export default {
	components: {
		'countdown-popo': countdownPopo
	},
	data() {
		return {
			option: this.$route.query,
			infoData: null,
			// 滚动条
			ops: {
				vuescroll: {},
				scrollPanel: {},
				rail: {
					keepShow: true
				},
				bar: {
					hoverStyle: true,
					onlyShowBarOnScroll: false, // 是否只有滚动的时候才显示滚动条
					background: '#F5F5F5', // 滚动条颜色
					opacity: 0.5, // 滚动条透明度
					'overflow-x': 'hidden'
				},
				videoData: []
			},

			// 表单
			form: {
				phone: '',
				discount: '',
				commission: '',
				// 出资方
				stakeLis: [
					{
						id: 0,
						label: '合作商户',
						txt: '出资方为合作商户指用户在合作商户消费享受的优惠是合作商户自己承担'
					},
					{
						id: 1,
						label: '本商户',
						txt: '出资方为本商户指用户在合作商户消费享受的优惠是需要本商户补贴给合作商户'
					}
				],
				stakeRadio: '',
				// 是否需要同意
				agreeLis: [
					{
						id: 0,
						label: '是',
						txt: '指合作商户是否需要知道参与了本商户的超级会员'
					},
					{
						id: 1,
						label: '否',
						txt: '指合作商户是否需要知道参与了本商户的超级会员'
					}
				],
				agreeRadio: '',
				// 积分奖励
				integralReward: [
					{
						id: 0,
						label: '订单售后不回收奖励积分'
					},
					{
						id: 1,
						label: '订单售后回收奖励积分'
					}
				],
				integralInput: '',
				integralRadio: 0,
				// 积分比例
				integralProp: '',

				canCustomRate: false,
				customMaxRate: '',
				customMinRate: '',
				specialRoleRate: ''
			},
			merchFlag: false,
			rules: {
				phone: [
					{
						required: true,
						validator: (rules, value, callback) => {
							const reg = /^[1][3-9][0-9]{9}$/;
							if (value == '' || value == undefined || value == null) {
								return callback(new Error('输入不可以为空'));
							} else {
								if (!reg.test(value) && value != '') {
									callback(new Error('请输入正确的手机号码'));
								} else if (this.merchFlag == true) {
									callback(new Error('输入手机号不是商户，请确认后再次输入'));
								} else {
									callback();
								}
							}
						},
						trigger: 'blur'
					}
				],
				stakeRadio: [{ required: true, message: '请选择出资方', trigger: 'blur' }],
				agreeRadio: [{ required: true, message: '请选择是否需要同意', trigger: 'blur' }],
				discount: [
					{
						required: true,
						validator: (rules, value, callback) => {
							if (!value) {
								return callback(new Error('输入不可以为空'));
							}
							setTimeout(() => {
								if (value < 0 || value > 9.9 || value.length > 3) {
									callback(new Error('只可输入1位小数正数，可输入范围0～9.9'));
								} else {
									callback();
								}
							}, 100);
						},
						trigger: 'blur'
					}
				],
				commission: [
					{
						required: true,
						validator: (rules, value, callback) => {
							setTimeout(() => {
								var result = value.toString().indexOf('.');
								if (!value || result != -1) {
									callback(new Error(`请输入${this.form.customMinRate} ~ ${this.form.customMaxRate}之间的整数`));
								} else if (value < this.form.customMinRate || value > this.form.customMaxRate) {
									callback(new Error(`请输入${this.form.customMinRate} ~ ${this.form.customMaxRate}之间的整数`));
								} else {
									callback();
								}
							}, 100);
						},
						trigger: 'blur'
					}
				],
				integralInput: [
					{
						required: true,
						validator: (rules, value, callback) => {
							setTimeout(() => {
								var result = value.toString().indexOf('.');
								if (!value || result != -1) {
									callback(new Error(`可输入0 ~ 9999,不可输入小数,输入0表示不奖励积分`));
								} else if (value < 0 || value > 9999) {
									callback(new Error(`可输入0 ~ 9999,不可输入小数,输入0表示不奖励积分`));
								} else {
									callback();
								}
							}, 100);
						},
						trigger: 'blur'
					}
				],
				integralProp: [
					{
						required: true,
						validator: (rules, value, callback) => {
							setTimeout(() => {
								var result = value.toString().indexOf('.');
								if (!value || result != -1) {
									callback(new Error(`可输入0 ~ 99,不可输入小数,输入0表示不可用积分抵扣`));
								} else if (value < 0 || value > 99) {
									callback(new Error(`可输入0 ~ 99,不可输入小数,输入0表示不可用积分抵扣`));
								} else if (isNaN(value)) {
									callback(new Error(`可输入0 ~ 99,不可输入小数,输入0表示不可用积分抵扣`));
								} else {
									callback();
								}
							}, 100);
						},
						trigger: 'blur'
					}
				]
			},
			loading: false,

			// 商户数据
			merchList: [],
			selectMerch: [],
			time: '',

			//积分配置
			pointsConfig: '',

			// 倒计时弹窗内容
			countdown: {
				num: null,
				jumpUrl: null,
				msg: null, // 邀请已经发送，请耐心等待商户处理。
				showPopup: false
			},

			// 补贴
			butieStatus: null
		};
	},
	computed: {
		...mapGetters(['userInfo'])
	},
	mounted() {
		// console.log('userInfo', this.userInfo)
		this.getBusinessInfoFun();
		this.getPointsConfigFun();
		const { id } = this.userInfo.business;
		this.businessId = id;
		// 抽佣比例
		this.getMokeFun();
	},
	methods: {
		/* 来自修改的数据 */
		getChangeFun() {
			if (this.option.rowConten) {
				let { merchPhone, stakeValue, discount, commission, integralAwar, recyclePoints, integralProportion, needAgree, joinBusinessId } = JSON.parse(
					this.option.rowConten
				);
				this.form.phone = merchPhone;
				this.form.stakeRadio = stakeValue == 1 ? 1 : 0;
				this.form.agreeRadio = needAgree ? 0 : 1;
				this.form.discount = String(discount);
				this.form.commission = String(commission);
				this.form.integralInput = String(integralAwar);
				this.form.integralRadio = recyclePoints ? 1 : 0;
				this.form.integralProp = String(integralProportion);
				this.form.joinBusinessId = joinBusinessId;

				if (this.form.agreeRadio == 1 && this.form.stakeRadio == 1) {
					this.form.canCustomRate = true;
					this.form.commission = '0';
				}
			}
		},

		/* 提交 */
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (this.form.stakeRadio == 1) {
					Promise.all([this.butieDialogFun()]).finally(() => {
						if (!this.butieStatus) {
							// 提交修改
							this.loading = true;
							this.getTimeFun();
							this.getNewInviteBusinessFun();
						}
					});
				} else {
					// 提交修改
					this.loading = true;
					this.getTimeFun();
					this.getNewInviteBusinessFun();
				}
			});
		},

		/* 重置 */
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		back() {
			this.$router.go(-1);
		},
		toSetVipPoints() {
			this.$router.push({ name: 'VipPoints', params: { changeType: 'spMbPoints', tabName: 'use' } });
		},

		/* 表单数据 */
		// 抽佣比例
		getMokeFun() {
			const businessId = this.businessId;
			getSuperMemberRateConfig({ businessId }).then(res => {
				// console.log('抽佣比例', res);
				if (res.data) {
					const { canCustomRate, customMaxRate, customMinRate, bkgeRate, specialRoleRate } = res.data;
					if (canCustomRate == 1) {
						this.form.canCustomRate = false;
					} else {
						this.form.canCustomRate = true;
						this.form.commission = bkgeRate;
					}
					this.form.customMaxRate = customMaxRate;
					this.form.customMinRate = customMinRate;
					this.form.specialRoleRate = specialRoleRate;

					this.getChangeFun();
				}
			});
		},

		//二次确定（就是原本有感，改为无感）
		getNewInviteBusinessFun() {
			const { needAgree } = JSON.parse(this.option.rowConten);
			let agreeRadio = this.form.agreeRadio;
			if (needAgree && agreeRadio == 1) {
				this.$confirm('是否确定把合作商户修改为不需要确定的无感合作？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						this.modifyDiscountAndRakeRateApiFun();
					})
					.catch(() => {
						this.loading = false;
					});
			} else {
				this.modifyDiscountAndRakeRateApiFun();
			}
		},

		// 修改商户请求
		modifyDiscountAndRakeRateApiFun() {
			const { id, needAgree } = JSON.parse(this.option.rowConten);
			let agreeRadio = this.form.agreeRadio;
			let stakeRadio = this.form.stakeRadio;
			const form = {
				deductionRatio: this.form.integralProp,
				discount: this.form.discount,
				financingParty: this.form.stakeRadio == 0 ? 2 : 1,
				id,
				needAgree: this.form.agreeRadio == 0 ? true : false,
				rakeRate: this.form.commission,
				recyclePoints: this.form.integralRadio == 0 ? false : true,
				rewardCoefficient: this.form.integralInput
			};

			modifyDiscountAndRakeRate(form)
				.then(res => {
					if (res.code == 0) {
						// console.log('stakeRadio - 出资方', stakeRadio);
						// console.log('agreeRadio - 是否需要同意', agreeRadio);
						// console.log('needAgree - 原来是否需要同意', needAgree);
						if (agreeRadio == 0 || stakeRadio == 0) {
							// 有感
							this.$alert(
								'<p>修改成功，需要合作商户确定。</p> <p>合作商户同意修改，用户到店消费将按照新规则享受优惠；</p><p>如合作商户拒绝修改，用户到店消费将按照原规则享受优惠。</p>',
								'提示',
								{
									dangerouslyUseHTMLString: true,
									callback: action => {
										this.$router.go(-1);
									}
								}
							);
						} else if (!needAgree && agreeRadio == 1) {
							//无感提示
							this.$alert('<p>修改成功，用户到合作商户消费将按照新规则享受优惠。</p>', '提示', {
								dangerouslyUseHTMLString: true,
								callback: action => {
									this.$router.go(-1);
								}
							});
						} else {
							this.$message({
								message: '修改成功！',
								type: 'success'
							});
							this.$router.go(-1);
						}
					}
				})
				.finally(() => {
					this.loading = false;
				});
		},

		//出资方
		changestakeRadio(e) {
			this.form.agreeRadio = null;
			Promise.all([this.butieDialogFun()]).finally(() => {
				if (!this.butieStatus) {
					if (e == 1 && !this.infoData.marketingAccount) {
						this.marketingAccountDialog();
						return;
					} else if (e == 1 && this.infoData.marketingAccount) {
						this.getSubsidyAccountBalanceFun();
						return;
					}
				}
			});
		},
		changeAgreeRadio(e) {
			if (e == 1) {
				this.form.canCustomRate = true;
				this.form.commission = '0';
			} else {
				this.form.canCustomRate = false;
			}
		},
		// 积分抵扣比例
		changeIntegralProp(e) {
			if (e > 0 && !this.infoData.marketingAccount) {
				this.marketingAccountDialog();
				return;
			} else if (e > 0 && this.infoData.marketingAccount) {
				this.getSubsidyAccountBalanceFun();
				return;
			}
		},

		//补贴关系弹框
		butieDialogFun() {
			return new Promise(resolve => {
				let prams = {
					joinBusinessId: this.form.joinBusinessId
				};
				checkSubsidyRelation(prams).then(res => {
					this.butieStatus = res.data;
					if (this.butieStatus) {
						this.$confirm('当前邀请商户已与其他商户绑定补贴关系，不可选择出资方为本商户', '提示', {
							cancelButtonText: '确定',
							type: 'warning',
							showConfirmButton: false
						})
							.then(() => {})
							.catch(() => {});
						this.form.stakeRadio = 0;
						this.form.integralProp = '0';
					}
					resolve();
				});
			});
		},

		// 营销账户弹框
		marketingAccountDialog() {
			this.$prompt(
				'请填写斗拱营销户账户号，如还没开通渠道营销户请点击下方链接开通：<a href="https://dashboard.huifu.com/customers/login" target="_blank" style="color:skyblue">https://dashboard.huifu.com/customers/login</a>',
				'提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					dangerouslyUseHTMLString: true
				}
			)
				.then(({ value }) => {
					this.marketingAccount = value;
					this.saveMarketingAccountFun();
				})
				.catch(() => {
					this.form.stakeRadio = 0;
					this.form.integralProp = '0';
				});
		},

		// 保存渠道营销户
		saveMarketingAccountFun() {
			let prams = {
				businessId: this.businessId,
				marketingAccount: this.marketingAccount
			};
			saveMarketingAccount(prams)
				.then(res => {
					// console.log('保存渠道营销户', res);
					if (res.code == 0) {
						this.getSubsidyAccountBalanceFun();
					}
				})
				.catch(() => {
					this.form.stakeRadio = 0;
					this.form.integralProp = '0';
				});
		},
		// 查询补贴账户余额
		getSubsidyAccountBalanceFun() {
			let prams = {
				businessId: this.businessId
			};
			getSubsidyAccountBalance(prams).then(res => {
				// console.log('查询补贴账户余额', res);
				if (res.code == 0) {
					if (res.data <= 0) {
						this.$confirm('当前补贴账户余额不足不可选择资方-本商户', '提示', {
							confirmButtonText: '立即充值',
							cancelButtonText: '确定',
							type: 'warning'
						})
							.then(() => {
								window.open('https://dashboard.huifu.com/customers/login');
								this.form.stakeRadio = 0;
								this.form.integralProp = '0';
							})
							.catch(() => {
								this.form.stakeRadio = 0;
								this.form.integralProp = '0';
							});
					}
				}
			});
		},

		// 商家信息相关
		getBusinessInfoFun() {
			getBusinessInfo().then(res => {
				console.log('商家信息相关', res);
				if (res.code == 0) {
					this.infoData = res.data;
				}
			});
		},

		//获取积分配置
		getPointsConfigFun() {
			getPointsConfig().then(res => {
				this.pointsConfig = res.data;
			});
		},

		// 获取当前时间
		getTimeFun() {
			const yy = new Date().getFullYear();
			const mm = new Date().getMonth() + 1;
			const dd = new Date().getDate();
			const hh = new Date().getHours();
			const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
			const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
			this.time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
		}
	}
};
</script>

<style lang="scss" scoped>
.inviterMerch {
	width: 100%;
	height: 100%;
	background-color: white;
	padding: 20px;

	.merch {
		width: 100%;
		max-height: 400px;
		overflow-y: scroll;
		/*滚动条样式*/
		&::-webkit-scrollbar {
			/*滚动条整体样式*/
			width: 2px; /*高宽分别对应横竖滚动条的尺寸*/
			height: 4px;
		}
		&::-webkit-scrollbar-thumb {
			/*滚动条里面小方块*/
			border-radius: 5px;
			-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
			background-color: $primary;
		}
		&::-webkit-scrollbar-track {
			/*滚动条里面轨道*/
			-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
			border-radius: 0;
			background: rgba(0, 0, 0, 0.1);
		}

		.list {
			max-width: 590px;
			overflow: hidden;
			background-color: $barSubBgc;
			border: 1px solid $primary;
			padding: 8px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 8px;
			color: #909399;

			.checkbox {
				float: left;
			}

			.conten {
				width: 90%;
				float: left;
				line-height: 20px !important;
				.top {
					width: 100%;
					overflow: hidden;
					display: flex;
					justify-content: space-between;
					margin-bottom: 20px;
				}
				.tip {
					color: red;
				}
			}
		}
	}

	.merchOption {
		background-color: $barSubBgc;
		border: 1px solid $primary;
		padding: 8px;
	}

	.commission {
		// width: 750px;
		p {
			line-height: 20px !important;
			color: #afafaf;
		}
	}

	/deep/.el-input__inner {
		padding: 0;
		text-align: center;
	}
}
</style>
